#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

void ChildRun()
{
    int cnt = 5;//count
    while (cnt--)
    {
        printf("I am child process, pid:%d, ppid:%d, cnt:%d\n", getpid(), getppid(), cnt);
        sleep(1);
    }

}

int main()
{
    pid_t id = fork();
    if (0 == id)
    {
        //child
        ChildRun();
        printf("child quit...\n");
        exit(0);
    }
    else //id是子进程的pid
    {
        //parent
        sleep(7);//为了看到子进程的Z状态
        //pid_t rid = wait(NULL);//等待子进程退出(Z僵尸), 参数是子进程退出信息(输出型参数),  不关心时, 传NULL
        int status = 0;
        pid_t rid = waitpid(-1, &status, 0);//-1等待任一个子进程(也可以指定pid), NULL是退出信息, 0是阻塞等待, 一直等
        if (-1 == rid)//等待失败
            printf("wait fail\n");
        else
            printf("wait success, child pid:%d\n", rid);
        sleep(2);
        printf("father exit_code:%d, exit_signal:%d\n", status>>8 & 0xff, status&0x7f);

    }

    return 0;
}
